<!--
 * @Author: 选择桌台组件
 * @Date: 2025-09-07 17:30:00
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-09-07 17:39:30
 * @Description: 选择桌台的公共组件，不包含弹框，可复用
-->

<template>
  <div class="select-desktop-container">
    <div class="title">选择桌台</div>
    <!-- 分类 -->
    <div class="paging-list-box" v-loading="categoryLoading">
      <div
        class="paging-list-item"
        :class="{ 'paging-list-item-active': pagingActiveIndex === pagingIndex }"
        @click="handleSelectPaging(pagingIndex, pagingItem)"
        v-for="(pagingItem, pagingIndex) in currentDesktopCategoryList"
        :key="pagingItem.id"
      >
        {{ pagingItem.name }}
      </div>
      <div class="paging-list-btn">
        <img
          class="left-btn"
          @click.stop="oneCatePreviousPage"
          src="@/assets/images/home/page-left-icon.png"
          alt=""
        />
        <img
          class="right-btn"
          @click.stop="oneCateNextPage"
          src="@/assets/images/home/page-right-icon.png"
          alt=""
        />
      </div>
    </div>
    <!-- 桌台列表 -->
    <div class="room-selected-box" v-loading="listLoading">
      <div class="room-selected-scroll-list" v-if="!isShowNoData">
        <div
          class="scroll-selected-list-item"
          v-for="(desk, index) in currentDesktopList"
          :key="desk.id + index"
          @click="handleSelectTable(index, desk)"
        >
          <div class="title-box">
            <div class="count">
              <span class="hall">{{ desk.is_use.text }}</span>
              <span v-if="desk.hadRecordList && desk.recordInfo">
                {{ desk.recordInfo.use_num || '0' }}
              </span>
              <span v-else>{{ desk.use_num || '0' }}</span>
              /<span>{{ desk.capacity }}人</span>
            </div>
          </div>
          <div class="desc-box">
            <div class="numberAndTag">
              <el-tooltip class="item" effect="dark" :content="desk.name" placement="top">
                <div class="number">{{ desk.name }}</div>
              </el-tooltip>
              <div class="tag" v-if="desk?.recordInfo?.recordType">
                {{ desk.recordInfo.recordType }}
              </div>
            </div>
          </div>
          <!-- 显示选中的图标 -->
          <img
            v-show="selectedTableIndex === index"
            class="choose-img"
            src="@/assets/images/home/xuanzhongzhuotai.png"
            alt=""
          />
        </div>
      </div>
      <!-- 暂无数据 -->
      <div class="no-data-box" v-else>
        <NotData desc="暂无可用桌台" />
      </div>
    </div>
    <div class="count-selected-box">
      <div class="total">
        <span v-show="currentDesktopList.length > 0">共{{ currentDesktopList.length }}台</span>
      </div>
    </div>
    <div class="selected-desc">
      <!-- 转台菜品描述 -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import NotData from '@/components/NotData/Index.vue'
import { fetchDeskList, fetchCategoryList } from '@/api/desktop'
import { isEmpty } from '@/utils/toolsValidate'

interface Props {
  visible?: boolean
}

interface Emits {
  (e: 'select', targetDeskId: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
})

const emit = defineEmits<Emits>()

// 分页专用索引
const pagingActiveIndex = ref(0)
// 选中桌台的索引
const selectedTableIndex = ref(-1)
// 桌台分类列表分页相关
const deskCategoryPageQuery = ref({
  // 一级分类的分页
  page: 1,
  limit: 4
})
// 判断一级分类是否还能继续下一页操作分页
const deskOneCategoryLastPage = ref(0)
// 桌台筛选查询的相关数据
const desktopFilterQuery = ref({
  // 桌台名称
  name: null,
  // 桌台状态,只筛选空闲中的状态
  is_use: 0,
  // 分页默认第一页
  page: 1,
  // 分区id
  category_id: null,
  // 每页条数
  limit: 20
})
// 是否显示暂无数据
const isShowNoData = ref(false)
// 桌台分类列表数据
const currentDesktopCategoryList = ref<any[]>([])
// 桌台列表数据
const currentDesktopList = ref<any[]>([])
// 选中的桌台id
const currentDesktopId = ref<any>(null)
// 桌台列表loading状态
const listLoading = ref<boolean>(false)
// 分类列表loading状态
const categoryLoading = ref<boolean>(false)

// 监听visible变化，初始化数据
watch(
  () => props.visible,
  newVal => {
    if (newVal) {
      initData()
    }
  }
)

// 组件挂载时初始化数据
onMounted(() => {
  if (props.visible) {
    initData()
  }
})

// 初始化数据
const initData = () => {
  // 获取桌台列表数据
  getDeskTopList()
  // 获取桌台分类数据
  getDesktopCategoryList()
  selectedTableIndex.value = -1
  currentDesktopId.value = null
  listLoading.value = false
  categoryLoading.value = false
}

// 操作分页筛选对应的分类
const handleSelectPaging = (index: number, item: any) => {
  pagingActiveIndex.value = index
  desktopFilterQuery.value.page = 1
  desktopFilterQuery.value.category_id = item.id === 0 ? null : item.id
  getDeskTopList()
}

// 选中对应的桌台
const handleSelectTable = (index: number, desk: any) => {
  currentDesktopId.value = desk.id
  selectedTableIndex.value = index
  // 直接触发选择事件
  emit('select', desk.id)
}

// 获取桌台分类数据
const getDesktopCategoryList = async () => {
  categoryLoading.value = true
  try {
    const res = await fetchCategoryList(deskCategoryPageQuery.value)
    if (res.status === 200 && !isEmpty(res?.data?.data)) {
      deskOneCategoryLastPage.value = res.data.last_page
      if (deskCategoryPageQuery.value.page === 1) {
        res.data.data.unshift({
          id: 0,
          name: '全部'
        })
      }
      currentDesktopCategoryList.value = res.data.data
    }
  } catch (error) {
    console.error('获取桌台分类失败:', error)
  } finally {
    categoryLoading.value = false
  }
}

// 获取桌台列表数据
const getDeskTopList = async () => {
  listLoading.value = true
  try {
    const res = await fetchDeskList(desktopFilterQuery.value)
    if (res.status === 200 && !isEmpty(res?.data)) {
      // 排空判断
      if (isEmpty(res.data?.data)) {
        isShowNoData.value = true
        currentDesktopList.value = []
        return
      }
      // 组装桌台列表
      const desktopArrList: any[] = []
      res.data.data.forEach((item: any) => {
        if (isEmpty(item.recordList)) {
          // 标记recordList为空
          item.hadRecordList = false
          desktopArrList.push(item)
        } else {
          // 标记recordList不为空
          item.hadRecordList = true
          item.recordList.forEach((record: any) => {
            const recordObj = {
              recordInfo: {
                ...record
              }
            }
            item = { ...item, ...recordObj }
            desktopArrList.push(item)
          })
        }
      })
      currentDesktopList.value = desktopArrList
      isShowNoData.value = false
    }
  } catch (error) {
    console.error('获取桌台列表失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 一级分类上一页操作
const oneCatePreviousPage = () => {
  if (deskCategoryPageQuery.value.page === 1) return
  deskCategoryPageQuery.value.page -= 1
  // 重置一级分类索引和桌台列表分页
  resetOneCate()
  getDesktopCategoryList()
}

// 一级分类下一页操作
const oneCateNextPage = () => {
  if (deskCategoryPageQuery.value.page >= deskOneCategoryLastPage.value) return
  deskCategoryPageQuery.value.page += 1
  // 重置一级分类索引和桌台列表分页
  resetOneCate()
  getDesktopCategoryList()
}

// 重置一级分类索引和桌台列表分页
const resetOneCate = () => {
  // 重置索引
  pagingActiveIndex.value = -1
  selectedTableIndex.value = -1
  currentDesktopId.value = null
  // 重置桌台列表的分页
  desktopFilterQuery.value.page = 1
  // 重置分类id
  desktopFilterQuery.value.category_id = null
  // 获取桌台列表数据
  getDeskTopList()
}

// 暴露方法给父组件调用
defineExpose({
  initData,
  getDeskTopList,
  getDesktopCategoryList
})
</script>

<style scoped lang="scss">
.select-desktop-container {
  box-sizing: border-box;
}

.title {
  font-size: 20px;
  font-family:
    PingFang SC,
    PingFang SC-Bold;
  font-weight: 700;
  text-align: left;
  color: #333333;
}

.paging-list-box {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 48px;
  background: #ffffff;
  border: 1px solid #d0d0d0;
  border-radius: 25px;
  display: flex;
  align-items: center;
  margin-top: 30px;

  .paging-list-item {
    display: inline-block;
    padding: 0 38px;
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #333333;
    cursor: pointer;
  }

  .paging-list-item-active {
    color: #ffffff;
    background: #7c0a03;
    border-radius: 24px;
  }

  .paging-list-btn {
    position: absolute;
    top: 12px;
    right: 16px;
    display: flex;
    align-items: center;

    .left-btn,
    .right-btn {
      flex-shrink: 0;
      width: 24px;
      height: 24px;
      cursor: pointer;
    }

    .left-btn {
      margin-right: 20px;
    }
  }
}

.room-selected-box {
  padding: 20px 24px 0 24px;
  box-sizing: border-box;
  height: 476px;
  width: 720px;
  overflow-y: auto;
  background: #f4f4f4;
  margin-top: 20px;
  border-radius: 12px;

  .room-selected-scroll-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-between;

    .scroll-selected-list-item {
      position: relative;
      width: 208px;
      height: 203px;
      background: #ffffff;
      border: 1px solid #d2d2d2;
      border-radius: 12px;
      box-sizing: border-box;
      border-top: none;
      margin-top: 20px;
      cursor: pointer;

      .title-box {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        height: 43px;
        background: #d2d2d2;
        padding: 0 12px;
        font-size: 13px;
        font-family:
          PingFang SC,
          PingFang SC-Bold;
        font-weight: 700;
        color: #ffffff;
        border-radius: 12px 12px 0px 0px;

        .count {
          display: flex;
          align-items: center;

          .hall {
            margin-right: 8px;
          }
        }
      }

      .desc-box {
        padding: 10px 0 0 12px;

        .numberAndTag {
          display: flex;
          align-items: flex-start;

          .number {
            max-width: 200px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            font-size: 36px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            color: #434447;
          }

          .tag {
            display: inline-block;
            padding: 0 10px;
            height: 20px;
            line-height: 20px;
            background: #cba699;
            border-radius: 10px 10px 10px 0px;
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            text-align: center;
            color: #ffffff;
            margin-left: 4px;
          }
        }
      }
    }

    .choose-img {
      position: absolute;
      right: 12px;
      bottom: 12px;
      width: 24px;
      height: 24px;
    }
  }

  .room-selected-scroll-list::after {
    content: '';
    width: 208px;
  }
}

//滚动条整体的大小
.room-selected-box::-webkit-scrollbar {
  width: 6px !important;
  height: 0 !important;
}

//滚动条里滑动的滑块
.room-selected-box::-webkit-scrollbar-thumb {
  height: 100px !important;
  background: #d2d2d2 !important;
  border-radius: 3px !important;
}

//滚动条底层样式
.room-selected-box::-webkit-scrollbar-track {
  display: none !important;
}

.count-selected-box {
  height: 60px;
  padding-left: 20px;
  box-sizing: border-box;
  background: #f4f4f4;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
  font-family:
    PingFang SC,
    PingFang SC-Regular;
  font-weight: 400;
  color: #333333;
}

.selected-desc {
  font-size: 18px;
  font-family:
    PingFang SC,
    PingFang SC-Regular;
  font-weight: 400;
  text-align: left;
  color: #333333;
  margin-top: 20px;
  padding: 0 20px;
}

.no-data-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  width: 100%;
}
</style>
